package java_thinking.unit_10._10_1_2;

/**
 * @Description : 连接到外部类
 * @author: cww
 * @DateTime: 2019-03-09 10:34
 */
public interface Selector {
    boolean end();

    /**
     * 获取Object的每个对象
     * @return
     */
    Object current();
    void next();
}
class Sequence {
    private Object[] items;
    private int next = 0;
    public Sequence(int size){
        items = new Object[size];
    }
    public void add(Object x){
        if(next<items.length){
            //[0,1,2,3,4,5,6,7,8,9]
            items[next++] = x;
        }
    }

    /**
     * 内部私有类
     */
    private class SequenceSelector implements Selector{
        private int i =0;

        /**
         * 检测长度
         * @return
         */
        @Override
        public boolean end() {
            return i == items.length;
        }

        /**
         * 访问当前对象
         * @return
         */
        @Override
        public Object current() {
            return items[i];
        }

        /**
         * 移动到序列中的下个对象
         */
        @Override
        public void next() {
            if (i<items.length){
                i++;
            }
        }

        /**
         * unit10 练习4在Sequence.SequenceSelector类添加一个方法可以生成外部类Sequence的引用
         * @return
         */
        public Sequence getSelector(){
            return Sequence.this;
        }
    }

    /**
     * 内部私有类新建返回给外部调用
     * @return
     */
    public Selector selector(){
        return new SequenceSelector();
    }

    public static void main(String[] args) {
        Sequence sequence = new Sequence(10);
        for (int i=0;i<10;i++){
            sequence.add(new StringHolder(Integer.toString(i)));
        }
        Selector selector = sequence.selector();
        while (!selector.end()){
            System.out.println(selector.current()+" ");
            selector.next();
        }
    }
}

class StringHolder{
    private String data;
    StringHolder(String data){
        this.data = data;
    }
    @Override
    public String toString(){
        return data;
    }
}
